<template>
    <div class="content">
        <levelbar></levelbar>
        <TableLayout form-title="">
        <div slot="form-title" class="table-title"></div>
            <el-form ref="form" :model="form" label-width="80px" slot="form">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="打卡日期">
                            <el-date-picker :clearable="false" style="width:100%" @change="onSubmitPick" :editable="false" v-model="form.startDate" align="right" type="date" placeholder="选择日期" :picker-options="pickerOptions1"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="this.schoolType == 0">
                        <el-form-item label="年级">
                            <el-select v-model="form.grade" placeholder="请选择年级" style="width:100%" @change="eventClass">
                                <el-option v-for="item in form.gradeList" :key="item.pId" :label="item.sName" :value="item.pId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班级">
                            <el-select v-model="form.className" placeholder="请选择班级" style="width:100%">
                                <el-option v-for="item in form.classNameList" :key="item.classId" :label="item.classNickName" :value="item.classId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="学生姓名">
                            <el-input v-model="form.studentsName" placeholder="请输入学生姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="时间段">
                          <el-select v-model="form.timeSlice" placeholder="请选择时间段" style="width:100%">
                            <el-option v-for="item in form.timeSliceList" :key="item.pId" :label="item.attendanceTimeStr" :value="item.pId"></el-option>
                          </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="top-line">
                    <el-col :span="4" :offset="20"> 
                        <el-button type="primary" class="top-btn" @click="onSubmit">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <!-- <div class="table-title" slot="table-title"></div> -->
            <div class="btnPosition">
              <el-button @click="upSubmit">导出</el-button>
            </div>
            <el-table :data="tableData" border style="width: 100%" v-loading="loading" ref="multipleTable">
                <el-table-column prop="studentName" align="center" label="学生姓名">
                  <template scope="scope">
                    {{!scope.row.studentName ? '--' : scope.row.studentName}}
                  </template>
                </el-table-column>
                <el-table-column prop="gradeName" align="center" label="年级">
                  <template scope="scope">
                    {{!scope.row.gradeName ? '--' : scope.row.gradeName}}
                  </template>
                </el-table-column>
                <el-table-column prop="className" align="center" label="班级">
                  <template scope="scope">
                    {{!scope.row.className ? '--' : scope.row.className}}
                  </template>
                </el-table-column>
                <el-table-column prop="date" align="center" label="日期">
                  <template scope="scope">
                    {{!scope.row.searchDate ? '--' : scope.row.searchDate}}
                  </template>
                </el-table-column>
                <!-- :render-header="renderHeader" -->
                <el-table-column align="center" label="" :render-header="renderHeader">
                    <el-table-column prop="checkinTime" align="center" label="签到时间">
                      <template scope="scope">
                        {{!scope.row.checkinTime ? '--' : scope.row.checkinTime.substring(0,5)}}
                      </template>
                    </el-table-column>
                    <el-table-column align="center" label="状态">
                      <template scope="scope">
                        <!-- 0:正常;1:迟到;2:早退;-1:缺卡-2未绑卡 -->
                        {{scope.row.checkinStatus == 0 ? '正常' : scope.row.checkinStatus == 1 ? '迟到' : scope.row.checkinStatus == 2 ? '早退' :  scope.row.checkinStatus == -1 ? '缺卡':scope.row.checkinStatus == -2 ? '未绑卡':'--'}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="checkoutTime" align="center" label="签退时间">
                      <template scope="scope">
                        {{!scope.row.checkoutTime ? '--' : scope.row.checkoutTime.substring(0,5)}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="checkoutStatus" align="center" label="状态">
                      <template scope="scope">
                        {{scope.row.checkoutStatus == 0 ? '正常' : scope.row.checkoutStatus == 1 ? '迟到' : scope.row.checkoutStatus == 2 ? '早退' :  scope.row.checkoutStatus == -1 ? '缺卡':scope.row.checkoutStatus == -2 ? '未绑卡':'--'}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="isLeave" align="center" label="备注">
                      <template scope="scope">
                        {{!scope.row.isLeave ? '--' : scope.row.isLeave == 1 ? '请假' : scope.row.isLeave}}
                      </template>
                    </el-table-column>
                </el-table-column>
            </el-table>
            <div class="pagination-container" style="text-align:right">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="listQuery.total"
                    :current-page.sync="listQuery.page"
                    :page-sizes="config.pageSizes"
                    :page-size="config.pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </TableLayout>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import TableLayout from 'components/TableLayout';
import startDate from 'components/Datepicker/startDate';
import endDate from 'components/Datepicker/endDate';
import { mapState, mapActions, mapGetters } from 'vuex';
import { getGradeList, getClassList } from 'api/studentMange';
import {
  listStundetAttendance,
  pageStundetCheckinfo,
  findSchoolFirstAttendance
} from 'api/attendanceManage';
export default {
    name: 'studentsAttendance',
    components: {
        Levelbar,
        TableLayout,
        startDate,
        endDate
    },
    data() {
        return {
            pickerOptions1: {
                disabledDate: time => {
                    let attendanceTime = this.attentiem - 3600 * 1000 *24;
                    if (attendanceTime) {
                        return time.getTime() < attendanceTime || time.getTime() > Date.now();
                    }
                },
                shortcuts: [
                    {
                        text: '今天',
                        onClick: picker => {
                            if (new Date() > this.attentiem) {
                                picker.$emit('pick', new Date());
                            } else {
                                this.$message('该时间段考勤记录尚未生成');
                            }
                        }
                    },
                    {
                        text: '昨天',
                        onClick: picker => {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24);
                            if (date> this.attentiem) {
                                picker.$emit('pick', date);
                            } else {
                                this.$message('该时间段考勤记录尚未生成');
                                picker.$emit('pick', new Date());
                            }
                        }
                    },
                    {
                        text: '一周前',
                        onClick: picker => {
                            const date = new Date();
                            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                            if (date > this.attentiem) {
                                picker.$emit('pick', date);
                            } else {
                                this.$message('该时间段考勤记录尚未生成');
                                picker.$emit('pick', new Date());
                            }
                        }
                    }
                ]
            },
            form: {
                timeSlice: '', // 时间段
                timeSliceList: [], // 时间段数组
                grade: '', // 年级
                gradeList: [], // 年级数组
                className: '', // 班级
                classNameList: [], // 班级数组
                studentsName: '', // 学生姓名
                startDate: '' // 打卡日期
            },
            timeout: null, // 开启定时器
            tableData: [],
            listQuery: {
        // 分页
                page: 1,
                total: 0
            },
            loading: false,
            timeTitle: '',
            attendanceTime: null, // 开通时间
            attentiem: null // 限制时间转换
        };
    },
    computed: {
        ...mapState({
            config: state => state.config.table
        }),
    // 全校  schoolType  0 普通学校 1 培训学校
        ...mapGetters(['schoolId', 'token', 'cardIsOpen', 'schoolType'])
    },
    created() {
        // this.initDate();
        if (this.cardIsOpen == 1) {
            // this.searchFetchData();
            // this.onSubmitPick();
            this.getTime()
        } else {
            this.$message('该服务未开通！');
            this.timeTitle = '该时间段考勤记录尚未生成'
        }

    // 判断是否是培训学校
        if (this.schoolType == 1) {
            this.eventClass(null)
        }
    },
    methods: {
    // 全局获取行数
        ...mapActions(['ChangePageSize']),
    // 分页
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.ChangePageSize(val);
            this.searchFetchData();
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.searchFetchData();
        },
        getTime() {
            findSchoolFirstAttendance(this.schoolId, '0').then(data => {
                if (data.data.content) {
                    this.attendanceTime = data.data.content.attendanceTime;
                    this.attentiem = new Date(this.attendanceTime).getTime();
                    //console.log(this.attendanceTime, '赋值');
                }
            }).then(() => {
                this.initDate();
            }).then(() => {
                if (this.attendanceTime) {
                    this.searchFetchData();
                    this.onSubmitPick();
                }
            }).catch(Error => {
                //console.log('没有设置时间');
            })
        },
    // 设置初始时间
        initDate() {
            // const end = new Date();
            const start = new Date();
            start.setTime(start.getTime());
            this.form.startDate = start;
      // 获取年级
            getGradeList(this.schoolId)
        .then(data => {
            this.form.gradeList = data.data.content;
            this.form.gradeList.unshift({ sName: '请选择' });
        })
        },
    // 获取时间段
        getListStundet() {
            listStundetAttendance(
        this.fifterDate(this.form.startDate),
        this.schoolId
      ).then(data => {
          this.form.timeSliceList = [];
          this.form.timeSlice = '';
          this.form.timeSliceList = data.data.content;
          if (data.data.content[0]) {
              this.form.timeSlice = data.data.content[0].pId;
              this.timeTitle = data.data.content[0].attendanceTimeStr
          } else {
              this.timeTitle = '该时间段考勤记录尚未生成'
          }
      })
        },
        onSubmitPick() {
            this.getListStundet()
        },
    // 获取班级
        eventClass(val) {
            getClassList(val, this.schoolId).then(data => {
                this.form.classNameList = data.data.content;
                this.form.classNameList.unshift({ classNickName: '请选择' });
            });
        },
    // 返回年月日时分秒
        fifterDate(date) {
            if (typeof date === 'string') {
                return date;
            } else {
                let month = this.addZero(date.getMonth() + 1 + '');
                let day = this.addZero(date.getDate() + '');
                return `${date.getFullYear()}-${month}-${day} 00:00:00`;
            }
        },
    // 补0
        addZero(str) {
            if (typeof str === 'string') {
                return str.length > 1 ? str : '0' + str;
            }
        },
        searchFetchData() {
            this.loading = true;
            pageStundetCheckinfo(
        this.fifterDate(this.form.startDate),
        this.schoolId,
        this.form.grade,
        this.form.className,
        this.form.studentsName,
        this.form.timeSlice,
        this.listQuery.page,
        this.config.pageSize
      )
        .then(data => {
            this.loading = false;
            this.tableData = data.data.content.pageResult.list;
            this.listQuery.total = data.data.content.pageResult.pagination.total;

          // 获取时间段
            this.form.timeSliceList.some(item => {
                if (item.pId == this.form.timeSlice) {
                    this.timeTitle = item.attendanceTimeStr
                }
            })
        })
        .catch(Error => {
            this.loading = false;
            this.tableData = [];
            this.listQuery.total = 0;
            this.timeTitle = '该时间段考勤记录尚未生成';
        });
        },
        onSubmit() {
            if (this.cardIsOpen == 1) {
                this.listQuery.page = 1;
                this.searchFetchData();
            } else {
                this.$message('该服务未开通！');
            }
        },
    // 变化的label
        renderHeader(createElement, { column }) {
            return (column.label = this.timeTitle);
        },
        upSubmit() {
            let token = this.token,
                schoolId = this.schoolId,
                searchDate = this.fifterDate(this.form.startDate),
                gradeId = this.form.grade,
                classId = this.form.className,
                studentName = this.form.studentsName;

            if (this.listQuery.total !== 0) {
                window.location.href = `${LOCAL_API.ly}/checkinfo/exportStundetCheckinfo?token=${token}&schoolId=${schoolId}&searchDate=${searchDate}&gradeId=${gradeId}&classId=${classId}&studentName=${studentName}`;
            } else {
                this.$message.warning('无数据，无法导出！'); 
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.content {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;
  .el-tag {
    margin-left: 5px;
    background: #f9f9f9;
    color: #444;
  }
  .formBtn {
    width: 100%;
    height: 70px;
    border-top: 1px solid #dddddd;
    position: relative;
  }
  .btnPosition {
    padding: 13px 0;
    float: left;
  }
  .footer {
    text-align: center;
    margin-top: 40px;
  }
  .footer .el-button {
    padding: 10px 40px;
  }
}
</style>